const OSS = require('ali-oss');
const path = require('path');
const getPutObject = require('./api');
const aliOss = async (pathFile, doneCallback, isTeshu = false) => {
    let qrerys = { region: 'oss-cn-hangzhou', bucket: 'hxkj-tv-navigation' };
    //
    return new Promise(async (resolve, reject) => {
        getPutObject(isTeshu ? qrerys : null).then((res) => {
            /**
             * 设置获取token请求成功回调
             */
            let result = null;
            try {
                let resdata = res.data;
                // console.log(resdata);
                if (resdata.code == 1) {
                    result = resdata.data;
                } else {
                    console.log(`resdata.data`);
                    console.log(resdata.data);
                    return;
                }
            } catch (e) {
                console.log('获取上传凭证失败' + e.message);
            }
            let client = new OSS({
                // region以杭州为例（oss-cn-hangzhou），其他region按实际情况填写。
                region: result.region,
                // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
                accessKeyId: result.accessKeyId,
                accessKeySecret: result.accessKeySecret,
                stsToken: result.securityToken,
                bucket: result.bucket,
                refreshSTSToken: async () => {
                    // 向您搭建的STS服务获取临时访问凭证。
                    const { data } = await getPutObject(isTeshu ? qrerys : null);
                    result = data.data;
                    console.log(data.data);
                    return {
                        accessKeyId: result.accessKeyId,
                        accessKeySecret: result.accessKeySecret,
                        stsToken: result.securityToken
                    };
                },
                // 刷新临时访问凭证的时间间隔，单位为毫秒。
                refreshSTSTokenInterval: 300000
            });
            console.log('开始上传');
            console.log(pathFile);
            const randoms = Math.floor(Math.random() * (100 - 1)) + 1;
            const currentName = 'userId' + '/' + 'yyzx-' + randoms + Date.now() + '.mp4';

            client
                .put(currentName, path.normalize(pathFile), {
                    progress: (p) => {
                        // 上传进度
                        console.log('上传进度' + p);
                        doneCallback(p, client);
                    }
                })
                .then((result) => {
                    // console.log('上传返回值');
                    // console.log(result);
                    const resData = {
                        url: result.url,
                        name: result.name,
                        type: 'mp4'
                    };
                    resolve(resData);
                })
                .catch(function (err) {
                    console.log(err);

                    if (err.name == 'cancel') {
                        console.log(`您已取消上传！`);
                    } else {
                        reject(err);
                        console.log(`上传失败，请重试或更换资源` + err.message);
                    }
                });
        });
    });
};

module.exports = aliOss;
